package com.hb.trade.api.routine.service.tenderdoc;

import cfca.sadk.util.EncryptUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.hb.core.pojo.Attachment;
import com.hb.core.pojo.Attachments;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.model.constant.CommonConstant;
import org.fzzn.core.service.ZipFileService;
import org.fzzn.core.util.IdUtil;

import java.io.File;

/**
 * 扫码解密操作类
 *
 * @author zhaojk
 */
@Slf4j
@Setter
@Getter
public class ScanQrTenderDocumentOption extends AbstractTenderDocumentOption {

    /**
     * 投标文件必须基于至少一个文件
     *
     * @param attachment
     */
    public ScanQrTenderDocumentOption(Attachment attachment) {
        super(attachment);
    }

    /**
     * 投标文件必须基于至少一个文件
     * 若传入集合, 则只取第一个文件
     *
     * @param attachments
     */
    public ScanQrTenderDocumentOption(Attachments attachments) {
        super(attachments);
    }

    /**
     * 解密投标文件
     *
     * @param encStr base64加密过的对称密钥
     */
    @Override
    public void decryptBase64(String encStr) throws Exception {
        // 先用base64转换一下
        String decodeStr = Base64.decodeStr(encStr);
        decrypt(decodeStr);
    }

    /**
     * 解密投标文件
     *
     * @param encStr 对称密钥
     */
    @Override
    public void decrypt(String encStr) throws Exception {
        File decFile = new File(CommonConstant.DECRYPT_FILE_PATH + "/" + ShiroUtil.getUsername() + "/tenderFile" + IdUtil.getId() + ".zip");
        if (!FileUtil.exist(decFile)) {
            FileUtil.touch(decFile);
        }

        // 读取投标文件
        ZipFileService instance = ZipFileService.getInstance(file);

        File itemFile = instance.getItemFile(ENC_TENDER_FILE_NAME);
        EncryptUtil.decryptFileByDES3(itemFile.getAbsolutePath(), decFile.getAbsolutePath(), encStr);

        if (FileUtil.exist(decFile)) {
            this.decFile = decFile;
            log.info("解密成功...{}", this.decFile.getAbsolutePath());
            return;
        }
        throw new Exception("投标文件解密失败");
    }

}
